#! /bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

blue() {
    echo -e "\033[34m\033[01m$1\033[0m"
}
green() {
    echo -e "\033[32m\033[01m$1\033[0m"
}
red() {
    echo -e "\033[31m\033[01m$1\033[0m"
}


blue "The domain name check starts ... "
doamin_list="github.com www.github.com raw.githubusercontent.com objects.githubusercontent.com github.global.ssl.fastly.net"
github_com_ip_list="52.69.186.44 140.82.113.3 13.114.40.48 140.82.121.3 52.78.231.108"
raw_githubusercontent_com_ip_list="185.199.108.133 185.199.109.133 185.199.110.133 185.199.111.133"
# proxy_golang_org_ip_list="172.217.24.49 142.251.42.241 172.253.63.141 142.250.114.141 216.58.212.145"
github_global_ssl_fastly_net_ip_list="199.232.69.194 151.101.129.194 146.75.29.194"
objects_githubusercontent_com_ip_list="185.199.108.133 185.199.109.133 185.199.110.133 185.199.111.133"

Check_Ip_Ping() {
    for ip in $ip_list; do    #for循环遍历数组
    num=1    #定义初始值
    while [ $num -le 3 ]; do
        old=$(cat /etc/hosts | grep "$ip")

        if ping -c 1 $ip >/dev/null; then
           echo "$ip $domain ：Ping is success" >> ping_result.txt  #if 判断如果ping通 则返回success 

           # 写入hosts - 判断是否已存在
           if [ -z "$old" ]; then
                if [ $domain == "github.com" ]; then
                    sudo echo "$ip github.com" >> /etc/hosts
                    sudo echo "$ip www.github.com" >> /etc/hosts
                else
                    sudo echo "$ip $domain" >> /etc/hosts
                fi
           fi
           break
        else
            # 存在，说明当前不管用，注释掉
           if [ ! -z "$old" ]; then
                sudo sed -i "s/${old}/#${old}/g" /etc/hosts
           fi
        fi
    done

    if [ ${#FALL[*]} -eq 3 ]          # if判断如果失败次数等于3 则返回Ping is failure
    then
        echo "${FALL[1]} Ping is failure!" >> ping_result.txt 
        unset FALL[*]
    fi
done
}

Check_Domain_Ping() {
    ping_count=3
    for domain in $doamin_list; do 
        if ! ping -c$ping_count $domain &>/dev/null; then
            # red "name lookup failed for $domain with $ping_count times "
            ip_list=`eval echo '$'${domain//./_}_ip_list`
            for ip_list in $ip_list; do
                Check_Ip_Ping
            done
            Check_Domain_Ping
        else
            green "$domain Check name resolve passed! "
        fi
    done
}

echo '' >　ping_result.txt
    [ -f /etc/resolv.conf ] && cp /etc/resolv.conf /etc/resolv.conf.$(date +%Y%m%d%H%M%S)
    cat > /etc/resolv.conf << EOF
nameserver 8.8.4.4
nameserver 114.114.114.114
EOF

for doamin_list in $doamin_list; do
    Check_Domain_Ping
done


